package net.xo68.coordinator.client;

import com.alipay.sofa.jraft.JRaftUtils;
import com.alipay.sofa.jraft.conf.Configuration;
import lombok.Data;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Properties;

/**
 * 客户端配置
 * @author wuxie
 * @version 2020-9-29
 */
@Data
public class CoordinatorClientConfig implements Serializable {

    private String groupId;
    private String cluster;

    /**
     * 超时毫秒数
     */
    private int timeoutMs;
    /**
     * 失败后最大重试次数
     */
    private int maxRetry;

    public CoordinatorClientConfig() {
    }

    public boolean loadFromFile(String file) throws IOException {
        try (FileInputStream fin = new FileInputStream(new File(file))) {
            Properties props = new Properties();
            props.load(fin);
            this.groupId = props.getProperty("groupId");
            this.cluster = props.getProperty("cluster");
            this.timeoutMs = Integer.valueOf(props.getProperty("timeoutMs", "0"));
            this.maxRetry = Integer.valueOf(props.getProperty("maxRetry", "0"));
            return this.verify();
        }
    }

    private boolean verify() {
        if (StringUtils.isBlank(groupId)) {
            throw new IllegalArgumentException("Blank groupId");
        }

        if (StringUtils.isBlank(cluster)) {
            throw new IllegalArgumentException("Blank conf");
        }
        Configuration initConf = JRaftUtils.getConfiguration(cluster);
        if (initConf.isEmpty()) {
            throw new IllegalArgumentException("Blank conf");
        }

        return true;
    }
}
